package homework.day09;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Classname: HomeWork03
 * @Author: bromide
 * @CreateTime: 2022/4/9--14:52
 * @Version: V1.0
 * @Description: 进阶
 * 实现读取浏览器发送过来的一行字符串
 * <p>
 * 可以参考day05晚课练习
 * 浏览器发送过来的内容的特点:
 * 1:内容全是英文，数字和符号，都是单字节编码的字符
 * 2:每一行字符串后面跟着两个不可见的字符:回车符和换行符
 * 而这两个字符对应的编码数字是13,10
 * 就好比'a'对应的编码数字是97
 * <p>
 * 因此可以连续读取若干字符，如果上次读取的字符==13
 * 本次读取的字符==10就可以停止，并将之前的字符组成一个
 * 字符串并输出
 */
public class HomeWork03 {
    private ServerSocket serverSocket;

    public HomeWork03() {
        try {
            serverSocket = new ServerSocket(8077);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            Socket socket = serverSocket.accept();
            InputStream in = socket.getInputStream();
            int i;
            char cur = 'a', pre = 'a';
            StringBuilder builder = new StringBuilder();
            while ((i = in.read()) != -1) {
                cur = (char) i;
                if (cur == 10 & pre == 13) {
                    break;
                }
                builder.append(cur);
                pre = cur;
            }
            String line = builder.toString().trim();
            System.out.println(line);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        HomeWork03 ho3 = new HomeWork03();
        ho3.start();
    }
}
